<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8000/hello");
        socket.onmessage = function (ev) {
            alert("连接开启");
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
            //连接开启
            socket.onopen = function (ev) {
                var rt = document.getElementById("responseText");
                rt.value = "连接开启"

            }
            //连接关闭
            socket.onclose = function (ev) {
                var rt = document.getElementById("responseText");
                rt.value = rt.value + "\n" + "连接关闭"
            }
        }
    } else {
        alert("当前浏览器不支持webSocket")
    }
    function send(message){
        if(!window.socket){
            return;
        }
        if(socket.readyState==WebSocket.OPEN){
            socket.send(message)
        }else{
            alert("连接没有开启")
        }
    }
</script>
<form onsumit="return false">
    <textarea name="message"></textarea>
    <input type="button" value="发生消息" onclick="send(this.form.message.value)">
    <textarea id="responseText"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>

</body>
</html>